import {Buffer} from "buffer";
import {Unsigned32} from "./Unsigned32";
import {AxdrOctetString} from "../asn1.axdr/AxdrOctetString";
import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";


export class SID implements AxdrType{


    dataCode : Buffer | null = null;
    indi : Unsigned32 | null = null;
    fdata : AxdrOctetString | null = null;

    constructor() {

    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(indi : Unsigned32, fdata : AxdrOctetString){
        this.indi = indi;
        this.fdata = fdata;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.indi = new Unsigned32();
        this.indi.set_const();
        codeLength += this.indi.decode(input);

        this.fdata = new AxdrOctetString();
        codeLength += this.fdata.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.indi != null && this.fdata != null){
                codeLength = 0;
                codeLength += this.fdata.encode(output);
                codeLength += this.indi.encode(output);
            }else{
                throw new Error("fdata || indi is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.indi != null && this.fdata != null) {
            return "sequence: {"+ "indi: " + this.indi + ", fdata: " + this.fdata  + "}";
        } else {
            return "indi || fdata is null";
        }
    }

}
